package com.itheima.web.manager;

import com.itheima.domain.db.User;
import com.itheima.service.db.UserService;
import com.itheima.util.ConstantUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * java
 */

@Service
public class TestSoulManager {

    @Reference
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void sendSMS(String telephone) {

        //1. 生成验证码
        //String code = RandomUtil.randomNumbers(6);
        String code = "123456";

        //2. 发送验证码
        //smsTemplate.sendSms(phone, code);
        System.out.println(code);

        //3. 保存验证码
        stringRedisTemplate.opsForValue().set(ConstantUtil.SMS_CODE + telephone, code, Duration.ofMinutes(5));

    }

    public String login(String telephone, String code) {

        //1. 校验验证码
        String codeFromRedis = stringRedisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + telephone);
        if (!StringUtils.equals(codeFromRedis, code)) {
            //比对失败,直接返回错误信息
            return "0";
        }

        //2.比对成功
        stringRedisTemplate.delete(ConstantUtil.SMS_CODE + telephone);//删除验证码

        User user = userService.findByPhone(telephone);

        if (user == null) {

            return "1";

        }

        return "ok";
    }
}
